package com.acwing.partition9;

import java.io.*;

/**
 * @author `RKC`
 * @date 2021/12/4 16:16
 */
public class AC876快速幂求逆元 {

    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
        String[] s = reader.readLine().split(" ");
        int n = Integer.parseInt(s[0]);
        while (n-- > 0) {
            s = reader.readLine().split(" ");
            long a = Long.parseLong(s[0]), p = Long.parseLong(s[1]);
            long res = quickPow(a, p - 2, p);
            if (a % p != 0) writer.write(res + "\n");
            else writer.write("impossible\n");
        }
        writer.flush();
    }

    private static long quickPow(long a, long k, long p) {
        long res = 1;
        while (k != 0) {
            if ((k & 1) == 1) res = res * a % p;
            k >>= 1;
            a = a * a % p;
        }
        return res;
    }
}
